from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.elements import BinaryExpression,BooleanClauseList
from sqlalchemy.sql import func

"""数据仓储类"""
class Repository(object):

    def __init__(self,entityType):
        super().__init__()
        # 初始化数据库连接

        self.engine = create_engine('sqlite:///DB/75Stability.db')
        # 创建session工厂
        self.DBSession = sessionmaker(bind=self.engine)
        # 创建session对象
        self.session = self.DBSession()
        # 事务标识
        self.transFlag = False
        # 对象类型
        self.entityType = entityType
        
    # 开始事务
    def beginTrans(self):
        self.transFlag = True

    # 提交事务
    def commitTrans(self):
        try:
            self.transFlag = False
            self.session.commit()
        except:
            self.session.rollback()

    # 新增数据
    def insert(self,entity):
        self.session.add(entity)
        if(not self.transFlag):
            self.session.commit()

    # 更新数据
    def update(self,entity):
        self.session.merge(entity)
        if(not self.transFlag):
            self.session.commit()

    # 删除操作
    def delete(self,where):
        self.session.query(self.entityType).filter(where).delete()
        if(not self.transFlag):
            self.session.commit()

    # 查询单个实体
    def findEntity(self,*where):
        if (type(*where) is BinaryExpression or type(*where) is BooleanClauseList):
            return self.session.query(self.entityType).filter(*where).first()
        else:
            return self.session.query(self.entityType).get(where)

    # 查询实体列表
    def findList(self,*where):
        return self.session.query(self.entityType).filter(*where)

    # 查询数量
    def findCount(self,*where):
        return self.session.query(func.count('*')).select_from(self.entityType).filter(*where).scalar()

    # 查询最大数
    def findMax(self,prop,*where):
        return self.session.query(func.max(prop)).select_from(self.entityType).filter(*where).scalar()

    # 执行Sql语句
    def execute(self,sql,*agrs):
        return self.session.execute(sql,*agrs)

